import axios from "axios";
import router from "@/router";
import store from "@/store";

const instance = axios.create({
    baseURL: "http://43.143.0.76:8889/api/private/v1",
    // 指定的超时时间
    timeout: 60000,
    headers: {
        post: {
            "Content-Type": 'application/x-www-form-urlencoded'
        }
    }
});
// 添加请求拦截器
instance.interceptors.request.use(
    function (config) {
        if (config.url !== '/login') {
            config.headers.Authorization = window.localStorage.getItem('token')
        }

        return config
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);
// 添加响应拦截器
instance.interceptors.response.use(
    config => {
        let userList = JSON.parse(sessionStorage.getItem('userList'))
        if (userList) {
            if (userList.token) {
                config.headers['authorization'] = userList.token
            }
        }
        return config
    },
    function (error) {
        // 超出 2xx 范围的状态码都会触发该函数。
        // 对响应错误做点什么
        return Promise.reject(error);
    }
);
 
export function ajax(options) {
    const { url, method = "GET", data = {} } = options;

    if (method.toUpperCase() === "GET") {
        return instance.get(url, { params: data });
    }

    if (method.toUpperCase() === "POST") {
        return instance.post(url, data);
    }

    if (method.toUpperCase() === "PUT") {
        return instance.put(url, data);
    }

    if (method.toUpperCase() === "DELETE") {
        return instance.delete(url, data);
    }
    if (method.toUpperCase() === "PUT") {
        return instance.delete(url, data);
    }
}
